/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-01
 * Time: 20:36
 */
class Solution29 {
    public String reorganizeString(String s) {
        int n = s.length();
        char[] ret = new char[n];
        // 用哈希数组模拟哈希表
        int[] hash = new int[26];
        int maxCount = 0,index = 0;
        char maxch = ' ';

        for(int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            hash[ch-'a']++;
            if(maxCount < hash[ch -'a']) {
                maxCount = hash[ch -'a'];
                maxch = ch;
            }
        }

        // 特殊判断
        if(maxCount > (n+1)/2) {
            return "";
        }

        for(int i = 0; i < maxCount;i++) {
            ret[index] = maxch;
            index += 2;
        }

        // 置空
        hash[maxch-'a'] = 0;

        for(int i = 0; i < 26; i++) {
            for(int j = 0; j < hash[i]; j++) {
                if(index >= n) {
                    index = 1;
                }
                ret[index] = (char)(i+'a');
                index += 2;
            }
        }
        return new String(ret);
    }
}
